<template>
	<view class="registerClient">
		<text class="title request">企业全称</text>
		<view class="inp">
			<van-field v-model="info.title" name="pattern" placeholder="请输入企业全称"
				 :error-message="error.title" />
		</view>

		<!-- <text class="title request">岗位类别</text>
		<view class="selectVant" @click="pickerShow('hangye')">
			<van-field readonly clickable name="zpyx" v-model="info.hangye" placeholder="请选择"
				:error-message="error.hangye" :right-icon="imgUrl + 'under.png'"/>
		</view>

		<text class="title request">招聘意向</text>
		<view class="selectVant" @click="pickerShow('gangwei')">
			<van-field readonly clickable name="zpyx" v-model="info.gangwei" placeholder="请选择"
				:error-message="error.gangwei"  :right-icon="imgUrl + 'under.png'"/>
		</view> -->

		<text class="title request">企业规模</text>
		<view class="selectVant" @click="pickerShow('guimo')">
			<van-field readonly clickable name="zpyx" v-model="info.guimo" placeholder="请选择"
				:error-message="error.guimo" :right-icon="imgUrl + 'under.png'" />
		</view>

		<text class="title request">企业简介</text>
		<view class="textareaVant">
			<van-field v-model="info.description" rows="4" autosize type="textarea" placeholder="请输入文字描述"
				:error-message="error.description" input-class="textareaInp" />
		</view>

		<text class="title request">企业地址:</text>
		<view class="selectVant mb10" @click="pickerShow('area')">
			<van-field readonly clickable name="area" v-model="info.city" placeholder="点击选择省市区"
				:error-message="error.city"  :right-icon="imgUrl + 'under.png'"/>
		</view>
		<view class="inp">
			<van-field v-model="info.addr" name="pattern" placeholder="填写详细地址" :error-message="error.addr" />
		</view>

		<text class="title request">联系人</text>
		<view class="inp">
			<van-field v-model="info.name" name="pattern" placeholder="请填写联系人" :error-message="error.name" />
		</view>

		<text class="title request">手机号（登录账号）</text>
		<view class="inp mb10">
			<van-field v-model="info.tel" type="number" name="pattern" placeholder="请填写手机号" :error-message="error.tel" />
		</view>

		<view class="inpBox">
			<view class="inp mb10">
				<van-field v-model="graphicsCodeVal" center clearable placeholder="请输入图形验证码" :error-message="error.tcode"  />
			</view>
			<view class="graphicsCodeBox" @click="updateGraphicsCode">
				<canvas canvas-id="graphicsCodeCanvas" id="graphicsCodeCanvas" v-if="!src"></canvas>
				<image :src="src" mode="" class="graphicsCodeCanvas" v-else></image>
			</view>
		</view>

		<view class="inpBox code">
			<view class="inp">
				<van-field v-model="info.code" type="number" name="pattern" placeholder="请输入验证码" :error-message="error.code" />
			</view>
			<view class="getCodeBox">
				<button class="btn" :class="{'disabled':isSend}" @click="sendCode">{{sendTitle || '获取验证码'}}</button>
			</view>
		</view>

		<text class="title request">上传营业执照</text>
		<view class="upImgBox">
			<van-uploader @afterRead="afterRead"  v-show="!info.businessLicense" ref="uploader"   >
				<view class="upBtn">
					<van-icon name="plus" />
				</view>
			</van-uploader>
			<view class="uploadImage" v-if="info.businessLicense" @click="uploadImage">
				<image :src="baseImage + info.businessLicense" mode="widthFix"></image>
			</view>
			<view class="error-message" v-if="error.businessLicense">
				营业执照是必填项
			</view>
		</view>

		<view class="formItem">
			<button class="submit" @click="submit">确认，提交审核</button>
		</view>

		<!-- 地址Select -->
		<van-popup position="bottom" :show="areaShowPicker">
			<van-area :areaList="areaList" @confirm="selectQydz" @cancel="onCelcel('area')" />
		</van-popup>
		
		<picker-view ref="pickerRef" :list="colums" @confirm="onConfirm"></picker-view>
	</view>
</template>

<script>
	import {
		getData
	} from "@/core/web-api/common.js"
	 
	// import { 
	// 	areaList
	// } from '@vant/area-data';
	
	 import { 
	 	areaList
	 } from '@/node_k/area-data/areadata';
	
	import {
		Mcaptcha
	} from '@/utils/mcaptcha';
	import {
		getOpenId,
		sendCodeFunc,
		qiyeRegister
	} from "@/core/web-api/login.js"
	import {
		getRnd,
		uploadFile,
		validateFunc,
		formatImage
	} from "@/utils/util.js"
	import {
		mapState
	} from "vuex";
	import PickerView from "@/components/PickerView.vue";
	
	export default {
		props:{
			openid:{
				type:String,
				default(){
					return ""
				}
			}
		},
		data() {
			return {
				colums:[],
				info: {
					addr: "", //详细地址			
					businessLicense: "", //营业执照			
					city: "", //城市/区域			
					code: "", // 手机短信验证码			
					description: "", // 企业简介			
					email: "", // 邮箱			
					// gangwei: "", // 意向岗位（多个之间，分割）			
					guimo: "", // 企业规模			
					// hangye: "", // 所属行业			
					logo: "", // 公司logo			
					name: "", // 联系人			
					openid: "", // 用户唯一标识			
					picdir: "", // 企业封面			
					province: "", // 省份			
					tel: "", // 手机号			
					title: "", // 公司名称			
					wechat: "", // 微信号
				},
				graphicsCodeVal: "",
				areaList: areaList,
				optionsMap: {
					guimoColums: [],
					// hangyeColums: [],
					// gangweiColums: [],
				},
				areaShowPicker: false,
				guimoShowPicker: false,
				hangyeShowPicker: false,
				gangweiShowPicker: false,
				time: 59,
				timer: null,
				sendTitle: "",
				isSend: false,
				error: {
					tcode:"",
					addr: "", //详细地址
					businessLicense: "", //营业执照			
					city: "", //城市/区域			
					code: "", // 手机短信验证码			
					description: "", // 企业简介			
					email: "", // 邮箱			
					// gangwei: "", // 意向岗位（多个之间，分割）			
					guimo: "", // 企业规模			
					// hangye: "", // 所属行业			
					logo: "", // 公司logo			
					name: "", // 联系人			
					openid: "", // 用户唯一标识			
					picdir: "", // 企业封面			
					province: "", // 省份			
					tel: "", // 手机号			
					title: "", // 公司名称			
				},
				mcaptcha: "",
				type:"",
				src:"",
			}
		},
		components:{
			PickerView 
		},
		methods: {
			
			formatterImageFunc(e){
				return formatImage(e)
			},
			uploadImage(){
				let that = this;
				uni.chooseImage({
					success:(e)=> {
						let obj = formatImage(e);
						uploadFile(obj[0]).then(res => {
							this.info.businessLicense = res
							uni.showToast({
								title:"上传成功"
							})
						})
					},
					fail() {
						uni.showToast({
							title:"上传失败",
							icon:"none"
						})
					}
				})
			},
			/**
			 * 发送验证码
			 */
			sendCode() {
				let code = validateFunc(this.info.tel, 'tel')
				console.log(code)
				if (code != 2) {
					uni.showToast({
						title: code == 0 ? "请输入手机号码" : "手机号码格式错误",
						icon: "none"
					})
					return;
				}
				let grapValid = this.grapValid();
				if (!grapValid) return;
				if (this.isSend) return;
				this.isSend = true;
				this.sendTitle = `${this.time}秒后重发`
				this.sendTel();
				this.timer = setInterval(() => {
					this.time--;
					this.sendTitle = `${this.time}秒后重发`
					if (this.time == 0) {
						clearInterval(this.timer);
						this.time = 60;
						this.isSend = false;
						this.sendTitle = "";
					}
				}, 1000)
			},
			/**
			 * 发送手机号验证码
			 */
			sendTel() {
				sendCodeFunc({
					phone: this.info.tel,
					type: "reg"
				}).then(res => {
					if (res.code == 20000) {
						uni.showToast({
							title: "发送成功"
						})
					}
				})
			},
			/**
			 * 弹出弹窗
			 * @param {Object} type
			 */
			pickerShow(type) {
				this.type = type;
				if(type!='area'){
					this.colums = this.optionsMap[type+"Colums"];
				}else{
					this.areaShowPicker = true;
					return;
				}
				if (type == 'gangwei') {
					if (!this.optionsMap.gangweiColums || this.optionsMap.gangweiColums.length == 0) {
						uni.showToast({
							title: "请选择岗位类别",
							icon: "none"
						})
						return;
					}
					this.$refs.pickerRef.open();
				} else{
					this.$refs.pickerRef.open();
				}
			},
			/**
			 * 上传图片
			 * @param {Object} 
			 */
			afterRead(e) {
				console.log(e);
				// uni.uploadFile({
				// 	url:this.$store.state.uploadUrl,
				// 	filePath:e.file.tempFilePath,
				// 	name:"file",
				// 	success:res=>{
				// 		console.log(res)
				// 	}

				// })
				uploadFile(e.file).then(res => {
					this.info.businessLicense = res;
				})
			},
			onCelcel(type) { 
				this.areaShowPicker = false;			 
			},
			onConfirm() {
				let value = this.$refs.pickerRef.value;
				if (this.type == 'hangye') {
					this.info.hangye = value;
					let index = this.optionsMap.hangyeColums.findIndex(f => f.sort == value);
					this.optionsMap.gangweiColums = this.optionsMap.hangyeColums[index].datasetTreeVos;
				}
				this.info[this.type] = value
			},
			/**
			 * 选择地址
			 */
			selectQydz({
				values
			}) {
				this.info.city = values
					.filter((item) => !!item)
					.map((item) => item.name)
					.join('/');
				this.areaShowPicker = false;
			},
			/**
			 * 切换图形验证码
			 */
			updateGraphicsCode() {
				this.src = "";
				this.mcaptcha.refresh()
				this.canvasToImage();
			},
			/**
			 * 验证码验证
			 */
			grapValid() {
				if (!this.graphicsCodeVal) {
					uni.showToast({
						title: '请输入图形验证码',
						icon: "none"
					})
					return false;
				}
				if (this.graphicsCodeVal.toLowerCase() != this.mcaptcha.options.createCodeImg.toLowerCase()) {
					uni.showToast({
						title: '图形验证码错误',
						icon: "none"
					})
					return false;
				}
				return true; 
			},
			/**
			 * 提交
			 */
			submit() {
		 
				let valid = this.validate();
				if (!valid) {
					uni.showToast({
						title: "有必填项未填",
						icon: "none"
					})
					return;
				}
				let grapValid = this.grapValid();
				if (!grapValid) return;
				
				qiyeRegister(this.info).then(res => {
					if (res.code == 20000) {
						this.$store.commit("setType",res.data.type);
						this.$store.commit("setToken",res.data.token);
						this.$parent.openRegister(3);
					} else {
						uni.showToast({
							title: res.message,
							icon: "none"
						})
					}
				})

			},
			validate() {
				const dist = {
					title: "企业全称",
					// hangye: "岗位类别",
					// gangwei: "招聘意向",
					guimo: "企业规模",
					description: "企业简介",
				    city: "企业地址",
					 addr: "详细地址",
					name: "联系人",
					tel: "手机号", 
					 code: "短信验证码",
					businessLicense: "营业执照",
				}
				let flag = true;
				for (let key in dist) {
					let code = validateFunc(this.info[key], key); 
					if (code == 0) {
						flag = false;
						this.error[key] = dist[key] + "为必填项"
					} else if (code == 1) {
						flag = false;
						this.error[key] = dist[key] + "格式错误"
					} else if (code == 2) {
						this.error[key] = "";
					}
				}
				if(!this.graphicsCodeVal){
					flag = false;
					this.error.tcode = "图形验证码为必填项";
				}else{
					this.error.tcode = "";
				}
				return flag;
			},
			/**
			 * 获取下级筛选
			 */
			getCataList() {
				let cataNames = ['招聘意向', '企业规模', '所属行业'];
				let cataList = ['gangweiColums', 'guimoColums', 'hangyeColums']
				getData({
					sortList: cataNames
				}).then(res => {
					console.log(res);
					let {
						list
					} = res.data;
					list.forEach(item => {
						let index = cataNames.findIndex(f => f == item.sort);
						this.optionsMap[cataList[index]] = item.list;
					})
				})
			},
			getIterative(arrs) {
				let arr = [];
				arrs.forEach(item => {
					arr[item.sort] = item.list.map(f => f.sort);
				})
				return arr;
			},
			
			canvasToImage(){
				let that = this;
				setTimeout(()=>{
					wx.canvasToTempFilePath({
						canvasId:'graphicsCodeCanvas',
						success:(res)=>{
							this.src = res.tempFilePath
							console.log(res)
						}
					},that)
				},300)
				
			}
			
		},
		computed: {
			...mapState(['openId', 'baseImage' ,'imgUrl'])
		},
		watch:{
			openid:{
				deep:true,
				immediate:true,
				handler(id){
					if(!id) return;
					this.info.openid = id;
				}
			},
			// mcaptcha:{
			// 	deep:true,
			// 	immediate:true,
			// 	handler(obj){
					
			// 		console.log(obj)
			// 	}
			// }
		},
		onReady() {
			this.mcaptcha = new Mcaptcha({
				el: 'graphicsCodeCanvas',
				width: 80,
				height: 35,
				createCodeImg: "",
				instance: this
			});
			this.canvasToImage();
		},
		created() {
			this.getCataList();
		}
	}
</script>

<style scoped lang="less">
	.request{
		position: relative;
		&::after{
			content: '*';
			position: absolute;
			left: -10upx;
			top: 0;
			font-size: 26upx;
			color: #ff0000;
		}
	}
	.registerClient {
		width: 100%;
		background: #fff;
		border-radius: 10px 10px 0px 0px;
		padding: 32px 31px 46px 28px;
		box-sizing: border-box;
		
	}

	.textareaInp {
		min-height: 60px;
	}

	.title {
		width: 100%;
		font-family: Microsoft YaHei;
		font-weight: 400;
		font-size: 16px;
		color: #000000;
		margin-bottom: 16px;
		padding-left: 5px;
		box-sizing: border-box;
		display: block;
	}

	.inp {
		width: 100%;
		background: #FFFFFF;
		border-radius: 5px;
		border: 1px solid #DCDCDC;
		box-sizing: border-box;
		margin-bottom: 23px;
	}

	.selectVant {
		width: 100%;
		background: #FFFFFF;
		border-radius: 5px;
		border: 1px solid #DCDCDC;
		position: relative;
		margin-bottom: 22px;
	}

	.selectVant::before {
		content: "";
		display: block;
		width: 20px;
		height: 16px;
		background-size: 100% 100%;
		position: absolute;
		top: 50%;
		margin-top: -9px;
		right: 15px;
		z-index: 1;
	}

	.textareaVant {
		width: 100%;
		max-height: 88px;
		background: #FFFFFF;
		border-radius: 5px;
		border: 1px solid #DCDCDC;
		box-sizing: border-box;
		margin-bottom: 22px;
	}

	.mb10 {
		margin-bottom: 10px !important;
	}

	.inpBox {
		width: 100%;
		position: relative;
	}

	.inpBox canvas {
		width: 100%;
		height: 100%;
	}

	.graphicsCodeBox {
		width: 87px;
		height: 45px;
		box-sizing: border-box;
		position: absolute;
		right: 0;
		top: 0;
		padding: 5px;
		z-index:2;
		image{
			width: 150upx;
			height: 70upx;
		}
	}

	.getCodeBox {
		position: absolute;
		right: 0;
		top: 0;
		height: 100%;
		padding: 7px 10px 0 0;
		box-sizing: border-box;
		z-index: 2;
	}

	.getCodeBox .btn {
		width: 80px;
		height: 30px;
		line-height: 30px;
		background: #F9F9F9;
		border-radius: 3px;
		border: 1px solid #0180FF;
		text-align: center;
		font-family: Microsoft YaHei;
		font-weight: 400;
		font-size: 24upx;
		color: #0180FF;
		padding: 0 10upx;
		box-sizing: border-box;

		&.disabled {
			background-color: #f5f5f5;
			border-color: #eee;
			color: #666;
		}
	}

	.upImgBox {
		width: 100%;
		height: auto;
		overflow: hidden;
		position: relative;
		margin-bottom: 60px;
	}

	.uploadImage {
		width: 100%;
	}

	.uploadImage image {
		width: 100%;
	}

	.upBtn {
		width: 153px;
		height: 103px;
		background: #E6E7E8;
		border-radius: 5px;
		border: 1px solid #DCDCDC;
		text-align: center;
		line-height: 103px;
		font-size: 31px;
	}

	.submit {
		width: 100%;
		height: 42px;
		line-height: 42px;
		text-align: center;
		background: #0180FF;
		border-radius: 5px;
		font-family: Microsoft YaHei;
		font-weight: 400;
		font-size: 16px;
		color: #FFFFFF;
	}
	.error-message{
		font-size: 24upx;
		color: #ee0a24;
		margin-top: 6upx;
	}
</style>